package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasJyzxxImportJyjxxEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasJyzxxImportJyjxxService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.vo.excel.GasJyzxxImportJyjxxExcel;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 基本信息
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-07-20 15:23:52
 */
@Controller
@RequestMapping("/gas/jyjxx")
@Slf4j
public class GasJyzxxImportJyjxxController {
	@Autowired
	private GasJyzxxImportJyjxxService gasJyzxxImportJyjxxService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private HttpSessionService httpSessionService;
	
	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
	
	@ApiOperation(value = "新增")
	@PostMapping("/add")
	// @RequiresPermissions("gasJyzxxImportJyjxx:add")
	@ResponseBody
	public DataResult add(@RequestBody GasJyzxxImportJyjxxEntity gasJyzxxImportJyjxx) {
		gasJyzxxImportJyjxxService.saveJyjxx(gasJyzxxImportJyjxx);
		return DataResult.success();
	}

	@ApiOperation(value = "删除")
	@DeleteMapping("/delete")
	// @RequiresPermissions("gasJyzxxImportJyjxx:delete")
	@ResponseBody
	public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
		gasJyzxxImportJyjxxService.removeByIdsJyjxx(ids);
		return DataResult.success();
	}

	@ApiOperation(value = "更新")
	@PutMapping("/update")
	// @RequiresPermissions("gasJyzxxImportJyjxx:update")
	@ResponseBody
	public DataResult update(@RequestBody GasJyzxxImportJyjxxEntity gasJyzxxImportJyjxx) {
		gasJyzxxImportJyjxxService.updateByIdJyjxx(gasJyzxxImportJyjxx);
		return DataResult.success();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/list")
	// @RequiresPermissions("gasJyzxxImportJyjxx:list")
	@ResponseBody
	public DataResult findListByPage(@RequestBody GasJyzxxImportJyjxxEntity gasJyzxxImportJyjxx) {
		Page page = new Page(gasJyzxxImportJyjxx.getPage(), gasJyzxxImportJyjxx.getLimit());
		LambdaQueryWrapper<GasJyzxxImportJyjxxEntity> queryWrapper = Wrappers.lambdaQuery();
		 //查询条件示例
        if(TsBqUtils.isNotNull(gasJyzxxImportJyjxx.getJcxxId())){
            queryWrapper.eq(GasJyzxxImportJyjxxEntity::getJcxxId, gasJyzxxImportJyjxx.getJcxxId());

        }else{
        	 return DataResult.fail("加油站ID为NULL");
        }
        
		IPage<GasJyzxxImportJyjxxEntity> iPage = gasJyzxxImportJyjxxService.page(page, queryWrapper);
		return DataResult.success(iPage);
	}
	
	
	@ApiOperation(value = "导出模板")
	@PostMapping("/exportTemplate")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult exportTemplate(@RequestBody GasStationinfoEntity vo) {

    	
		String currentDeptId = httpSessionService.getCurrentDeptId();

		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 市局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
		}else{
			//  省局
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}

		List<GasStationinfoEntity> list = gasStationinfoService.list(queryWrapper);

		if (list.size() > 0) {
			List<GasJyzxxImportJyjxxExcel> excelList = new ArrayList<>();
			for (GasStationinfoEntity entity : list) {

				GasJyzxxImportJyjxxExcel jyzxx = GasJyzxxImportJyjxxExcel.builder()
						.name(entity.getName())
						.jcxxId(entity.getId())
						.jyjMc("")
						.jyjXh("")
						.jyjZt("")
						.qysj("")
						.jyq1("")
						.jyq2("")
						.jyq3("")
						.jyq4("")
						.jyjwgZp("")
						.build();
				
				excelList.add(jyzxx);
			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, GasJyzxxImportJyjxxExcel.class);
				sheet1.setSheetName("数据");
				writer.write(excelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);

				return DataResult.success(excelFileInfo);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return DataResult.fail("xlsx生成失败：" + e.toString());
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return DataResult.fail("xlsx生成失败：" + e.toString());
				}
			}
		} else {
			return DataResult.fail("传入的ids为null！");
		}
	}
	
	@ApiOperation(value = "导入数据")
	@PostMapping("/importData")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult importData(@RequestParam("file") MultipartFile[] files) {

		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {
				InputStream inputStream = null;
				try {
					inputStream = file.getInputStream();
					Sheet sheet = new Sheet(1, 1);
					List<Object> readList = EasyExcelFactory.read(inputStream, sheet);
					List<GasJyzxxImportJyjxxEntity> jyjxxList = new ArrayList<>();

					for (Object object : readList) {
						List<String> list = TsBqUtils.castList(object, String.class);
						
						String name = list.get(0); // value = "加油站名称", index = 1)
						
						String jcxxId = list.get(1); // value = "加油站id-维护字段--主键", index = 2)
						
						String jyjMc = list.get(2); // value = "加油机名称", index = 3)
						
						String jyjXh = list.get(3); // value = "型号", index = 4)
						
						String jyjZt = list.get(4); // value = "加油机状态", index = 5)
						
						String qysj = list.get(5); // value = "启用时间", index = 6)
						
						String jyq1 = list.get(6); // value = "加油枪1号", index = 7)
						
						String jyq2 = list.get(7); // value = "加油枪2号", index = 8)
						
						String jyq3 = list.get(8); // value = "加油枪3号", index = 9)
						
						String jyq4 = list.get(9); // value = "加油枪4号", index = 10)
						
						String jyjwgZp = list.get(10); // value = "加油机外观-照片", index = 11)
						
						
						log.info("正在处理加油站：" + name + ",ID:" + jcxxId);
						if (TsBqUtils.isNull(jcxxId)) {
							return DataResult.fail("表格中存在【加油站jcxxId】为空的！");
						}
						
						GasJyzxxImportJyjxxEntity jyjxx = new GasJyzxxImportJyjxxEntity();
						jyjxx.setJcxxId(jcxxId); //
						jyjxx.setJyjMc(jyjMc); // 
						jyjxx.setJyjXh(jyjXh); // 
						jyjxx.setJyjZt(jyjZt); // 
						jyjxx.setQysj(qysj); // 
						jyjxx.setJyq1(jyq1); // 
						jyjxx.setJyq2(jyq2); // 
						jyjxx.setJyq3(jyq3); // 
						jyjxx.setJyq4(jyq4); // 
						jyjxx.setJyjwgZp(jyjwgZp); //
						          
						jyjxxList.add(jyjxx);
					}
					
					for (GasJyzxxImportJyjxxEntity entity : jyjxxList) {
						gasJyzxxImportJyjxxService.saveJyjxx(entity);
						
					}

				} catch (Exception e) {
					log.error("importData" + e.getMessage());
					
				} finally {
					if (inputStream != null) {
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
							return DataResult.fail(e.getMessage());
						}
					}
				}
			}
		}

		return DataResult.success();
	}
}
